<script setup>
/*
  forum 论坛页面 展示分类 + 文章列表
*/
import { getTabBrHeight } from "@/utils/system.js";
import { ref } from "vue";
import { apiGetSort, apiSortIdSearch } from "@/api/forum.js";
import { onShow, onHide, onReachBottom, onLoad, onUnload } from "@dcloudio/uni-app";
import articleItem from "@/components/article-item/article-item.vue";
import { storeToRefs } from "pinia";
import { useForumStore } from '@/store/forum.js'
import { useUserStore } from "@/store/user.js";
import useUserAction from "@/hooks/useUserAction";
// 用户行为
const { ensureLogin } = useUserAction()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const forumStore = useForumStore();
const { articleList } = storeToRefs(forumStore)
// 请求文章 -- 查询参数
let articleParams = {
  userId: userInfo.value?.id ?? 0,
  sortId1: 0, sortId2: 0,
  sortId3: 0,
  pageNum: 1,
  pageSize: 6
}
// 数据是否加载完毕
const noData = ref(false)
//初始化渲染页面
onLoad(() => {
  //获取分类
  getSort();
  //初次进入页面，将所有文章请求回来
  getArticle({ userId: userInfo.value?.id ?? 0, pageSize: 6, pageNum: 1 });
});
//获取文章列表
// const articleList = ref([]);
const getArticle = async (data = {}) => {
  uni.showLoading({
    title: '加载中',
    mask: true
  })
  //处理三级分类 + 富文本编辑器的图片
  const typeMap = {
    1: "速成",
    2: "精讲",
    3: "入门",
    4: "复习",
    5: "进阶",
    6: "技巧",
  };
  const res = await apiSortIdSearch(data);
  if (res.rows.length < articleParams.pageSize) {
    uni.hideLoading()
    noData.value = true
  }
  if (res.rows.length === 0) {
    uni.hideLoading()
    noData.value = true
    return
  }
  articleList.value = [...articleList.value, ...res.rows]
  articleList.value = articleList.value.map((item) => {
    item.sortName3 = typeMap[item.sortId3] || ""; // 可设置默认值
    // 新增字段：用于显示的预览内容（去掉图片）
    const previewContent = item.content.replace(/<img[^>]*>/g, "");

    return {
      ...item,
      previewContent, // 新增字段，不影响原 content
    };
  });

  setTimeout(() => {
    uni.hideLoading()
  }, 50);
};
//分类高亮
const activeSort1 = ref(0);
const activeSort2 = ref(0);
const activeSort3 = ref(0);
//目前选中的分类
const currentSortId1 = ref(0);
const currentSortId2 = ref(0);
const currentSortId3 = ref(0);
//一级分类
const firstCategory = ref([
  { sortId1: 0, name: "全部" },
  { sortId1: 1, name: "计算机" },
  { sortId1: 2, name: "英语" },
]);
//二级分类
const secondCategory = ref([]);
// 三级分类
const thirdCategory = ref([
  { sortId3: 0, name: "全部" },
  { sortId3: 1, name: "速成" },
  { sortId3: 2, name: "精讲" },
  { sortId3: 3, name: "入门" },
  { sortId3: 4, name: "复习" },
  { sortId3: 5, name: "进阶" },
  { sortId3: 6, name: "技巧" },
]);
//获取一级分类
const getSort = async () => {
  const res = await apiGetSort();
  // console.log("一级分类", res);
  firstCategory.value = [{ sortId1: 0, name: "全部" }, ...res];
};

//切换一级分类 -- 获取二级分类 -- 显示文章
const handleChangeSort1 = async (sortId1, index) => {
  articleList.value = []
  articleParams.pageNum = 1
  noData.value = false
  activeSort1.value = index;
  // 二三级分类/样式置空
  activeSort2.value = 0;
  currentSortId2.value = 0;
  articleParams.sortId2 = currentSortId2.value
  activeSort3.value = 0;
  currentSortId3.value = 0;
  articleParams.sortId3 = currentSortId3.value
  // 是否为重复请求
  if (currentSortId1.value === sortId1) return;
  currentSortId1.value = sortId1;
  articleParams.sortId1 = currentSortId1.value
  // 如果 id 为 0 那就请求所有文章
  if (!sortId1) {
    // console.log();
    console.log('全部', articleParams);
    console.log('apiAticleLIst:', articleParams);
    articleParams = {
      userId: userInfo.value?.id ?? 0,
      sortId1: 0,
      sortId2: 0,
      sortId3: 0,
      pageNum: 1,
      pageSize: 6
    }
    getArticle(articleParams);
    return;
  }
  // 不为 0 
  // 获取二级分类列表
  const res = await apiGetSort({ sortId1 });
  secondCategory.value = [{ sortId2: 0, name: "全部" }, ...res];
  //获取文章
  console.log(articleParams);
  await getArticle(articleParams);
};
//切换二级分类 -- 显示文章
const handleChangeSort2 = async (sortId2, index) => {
  articleList.value = []
  articleParams.pageNum = 1
  noData.value = false
  activeSort2.value = index;
  // 三级分类/样式置空
  activeSort3.value = 0;
  currentSortId3.value = 0;
  articleParams.sortId3 = 0
  // 是否为重复请求
  if (currentSortId2.value === sortId2) return
  currentSortId2.value = sortId2;
  articleParams.sortId1 = currentSortId1.value
  articleParams.sortId2 = currentSortId2.value

  //获取文章
  await getArticle(articleParams);
};
//点击三级分类 -- 显示文章
const handleChangeSort3 = async (sortId3, index) => {
  articleList.value = []
  articleParams.pageNum = 1
  noData.value = false
  activeSort3.value = index;
  // 是否为重复请求
  if (currentSortId3.value === sortId3) return
  currentSortId3.value = sortId3;
  // let params = { sortId3: sortId3 };
  articleParams.sortId3 = sortId3
  if (currentSortId1.value) articleParams.sortId1 = currentSortId1.value;
  if (currentSortId2.value) articleParams.sortId2 = currentSortId2.value;
  //获取文章
  await getArticle(articleParams);
};

//发布文章-跳转至富文本编辑器页面
const handlePublish = () => {
  if (!ensureLogin()) return
  uni.navigateTo({
    url: "/pages/publish/publish",
  });
};


//触底加载
onReachBottom(() => {
  console.log(123);
  if (noData.value) {
    return uni.showToast({
      title: '没有更多数据了',
      icon: 'none'
    })
  }
  articleParams.pageNum++
  getArticle(articleParams)
})

onUnload(() => {
  activeSort1.value = 0
  activeSort2.value = 0
  activeSort3.value = 0
  currentSortId1.value = 0
  currentSortId2.value = 0
  currentSortId3.value = 0
  articleList.value = []
})
</script>

<template>
  <view class="forum-container">
    <!-- 分类区域 -->
    <view class="sortBox">
      <!-- 一级分类 -->
      <template v-if="firstCategory">
        <scroll-view scroll-x class="scrollBox" :show-scrollbar="false" enable-flex>
          <!-- activeSort1 = index -->
          <view v-for="(item, index) in firstCategory" :key="item?.sortId1"
            @click="handleChangeSort1(item.sortId1, index)" class="forum-btn-sort">
            <view class="tag-view" :class="{ active: activeSort1 === index }">{{
              item.name
            }}</view>
          </view>
        </scroll-view>
      </template>

      <!-- 二级分类 -->
      <template v-if="currentSortId1">
        <scroll-view scroll-x class="scrollBox" :show-scrollbar="false" enable-flex>
          <view v-for="(item, index) in secondCategory" :key="item.sortId2" class="forum-btn-sort">
            <view class="tag-view" :class="{ active: activeSort2 === index }"
              @click="handleChangeSort2(item.sortId2, index)">
              {{ item.name }}
            </view>
          </view>
        </scroll-view>
      </template>
      <!-- 三级分类 -->
      <scroll-view scroll-x class="scrollBox" :show-scrollbar="false" enable-flex>
        <view v-for="(item, index) in thirdCategory" :key="item.sortId3" class="forum-btn-sort">
          <view class="tag-view" :class="{ active: activeSort3 === index }"
            @click="handleChangeSort3(item.sortId3, index)">
            {{ item.name }}
          </view>
        </view>
      </scroll-view>
    </view>
    <!-- 帖子列表 -->
    <view class="article-list">
      <template v-if="articleList.length > 0">
        <articleItem v-for="item in articleList" :key="item.id" :item="item"></articleItem>
      </template>
    </view>
    <!-- 发布帖子按钮 -->
    <view class="pubulish" :style="{ bottom: getTabBrHeight() + 'px' }" @click="handlePublish">
      <uni-icons type="plusempty" size="22" color="#fff"></uni-icons>
    </view>
  </view>
  <!-- 触底数据加载完毕 -->
  <view class="loadingLayout" v-if="articleList.length || noData">
    <uni-load-more :status="noData ? 'noMore' : 'loading'"></uni-load-more>
  </view>
</template>

<style scoped lang="scss">
.forum-container {
  padding: 0 30rpx;
  // min-height: 100vh;
  background: #fafafa;
  box-sizing: border-box;

  // 分类区域
  .sortBox {
    padding-top: 20rpx;
    // padding-bottom: 10rpx;
    position: sticky;
    top: 0rpx;
    background-color: #fafafa;
    z-index: 100;

    >.scrollBox {
      display: flex;
      flex-wrap: nowrap;
      overflow-x: auto;
      white-space: nowrap;
      scrollbar-width: none;
      min-height: 65rpx;

      &::-webkit-scrollbar {
        display: none;
      }

      .forum-btn-sort {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        margin-right: 16rpx;

        .tag-view {
          transition: all 0.25s ease;
          background-color: #f5f5f5;
          color: #333;
          border-radius: 999rpx;
          padding: 12rpx 28rpx;
          font-size: 26rpx;
          border: 1rpx solid transparent;
          margin-left: 2rpx;

          &:active {
            transform: scale(0.97);
          }

          &.active {
            background: linear-gradient(135deg, #4b9ffa, #2a6efc);
            color: #fff;
            font-weight: 500;
            box-shadow: 0 4rpx 10rpx rgba(42, 110, 252, 0.3);
            transform: scale(1.05);
            border: none;
          }
        }
      }
    }
  }

  //文章列表
  .article-list {
    margin-top: 15rpx;
    display: flex;
    flex-direction: column;
    gap: 24rpx; // 卡片间距
  }

  // 发布按钮
  .pubulish {
    width: 110rpx;
    height: 110rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    left: 50%;
    transform: translate(-50%, 0);
    background: linear-gradient(135deg, #3b82f6, #2563eb);
    border-radius: 50%;
    box-shadow: 0 12rpx 25rpx rgba(59, 130, 246, 0.35);
    z-index: 99;
    animation: fadeInUp 0.6s ease both;

    uni-icons {
      transition: transform 0.3s ease;
    }

    &:active uni-icons {
      transform: rotate(90deg) scale(1.1);
    }
  }
}

// 发布按钮浮现动画
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translate(-50%, 80rpx) scale(0.9);
  }

  to {
    opacity: 1;
    transform: translate(-50%, 0) scale(1);
  }
}
</style>
